//
//  UITextView+Category.swift
//  表情键盘
//
//  Created by Jacky Sun on 16/5/27.
//  Copyright © 2016年 syf. All rights reserved.
//

import UIKit

extension UITextView{
    
    func insertEmotion(emotion: Emotion, fontSize: CGFloat){
        
        if emotion.ISDeleteBtn{
            deleteBackward()
        }
        
        // 就是emoji表情
        if emotion.emojiStr != nil{
            self.replaceRange( self.selectedTextRange!, withText: emotion.emojiStr!)
        }
        // 图片表情
        if emotion.png != nil{
            
            // 创建附件对象
            let attach = EmojiAttachment()
            attach.chs = emotion.chs
            attach.image = UIImage(contentsOfFile: emotion.imgPath!)
            attach.bounds = CGRect(x: 0, y: -4, width: fontSize, height: fontSize)
            let imgStr = NSAttributedString(attachment: attach)
            
            // 取出textview的所有文本
            let  allStr = NSMutableAttributedString(attributedString: self.attributedText)
            let range = self.selectedRange
            allStr.replaceCharactersInRange(range, withAttributedString: imgStr)
            
            // 设置图片表情的装为attribute字符的字体大小
            allStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(CGFloat(fontSize-1)), range: NSMakeRange(range.location, 1))
            
            self.attributedText = allStr
            // 回复光标所在位置
            self.selectedRange = NSMakeRange(range.location + 1, 0)
            
            // 主动触发代理方法
            self.delegate?.textViewDidChange!(self)
        }

    }
    
    
    func getLookOverText() ->String{
        
        var str = String()
        
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0))
        { (dict, range, _) in
            //              print(dict)
            //              print(range)
            
            // 如果字典中有 NSAttachment 属性代表attribute里面有图片附件
            if dict["NSAttachment"] != nil{
                let attach = dict["NSAttachment"] as! EmojiAttachment
                str += attach.chs!
            }
            else{
                str += (self.text as NSString) .substringWithRange(range)
            }
        }
        
        print(str)
        return str
       
    }
}